package repository.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import repository.FriendRequestRepository;
import domain.FriendRequest;
import domain.User;
import domain.exceptions.DuplicateException;

@Repository
public class FriendRequestRepositoryImpl extends AbstractHibernateRepository<FriendRequest> implements FriendRequestRepository {

	@Autowired
	public FriendRequestRepositoryImpl(SessionFactory sessionFactory) {
		super(sessionFactory);
	}
	
	@Override
	public void newFriendRequests(FriendRequest fReq) throws DuplicateException {
		String hql = "FROM FriendRequest f WHERE requester=? AND requested=?";
		if (find(hql, fReq.getRequester(), fReq.getRequested()).size() > 0) {
			throw new DuplicateException();
		}
		save(fReq);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> getFriendRequestsByUser(User user) {
		Criteria crit = getSession().createCriteria(FriendRequest.class);
		Map<String, User> rest = new HashMap<String, User>();
		rest.put("requester", user);
		crit.add(Restrictions.allEq(rest));
		ProjectionList proList = Projections.projectionList();
		proList.add(Projections.property("requested"));
		crit.setProjection(proList);
		return crit.list();
	}

	@Override
	public List<FriendRequest> getFriendRequestsForUser(User user) {
		String hql = "FROM FriendRequest f WHERE requested=? ORDER BY f.requester.name DESC";
		return find(hql, user);
	}

	@Override
	public void deleteFriendRequest(FriendRequest fReq) {
		delete(fReq);
	}

	@Override
	public FriendRequest get(int id) {
		return get(FriendRequest.class, id);
	}
}
